package stackoverflow.domain.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import stackoverflow.domain.user.User.UserRole;

@Service("userAssemblerImpl")
public class UserAssembler {

	@Transactional(readOnly = true)
	User buildUserFromUserEntity(
			stackoverflow.domain.user.User applicationUserEntity) {

		String username = applicationUserEntity.getUserName();
		String password = applicationUserEntity.getPassword();
		boolean enabled = applicationUserEntity.getIsActive();
		boolean accountNonExpired = applicationUserEntity.getIsActive();
		boolean credentialsNonExpired = applicationUserEntity.getIsActive();
		boolean accountNonLocked = applicationUserEntity.getIsActive();

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (UserRole role : applicationUserEntity.getRoles()) {
			authorities.add(new GrantedAuthorityImpl(role.toString()));
		}

		return new User(username, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);
	}
}